<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :destroyOnClose="true"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="父级节点" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-tree-select
            ref="treeSelect"
            placeholder="请选择父级节点"
            v-decorator="['pid', validatorRules.pid]"
            dict="sys_category,name,id"
            pidField="pid"
            pidValue="0">
          </j-tree-select>
        </a-form-item>
        <a-form-item label="分类名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'name', validatorRules.name]" placeholder="请输入分类名称"></a-input>
        </a-form-item>
        <a-form-item v-if="fillRuleId === null" label="分类编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'code', validatorRules.code]" placeholder="请输入分类编码">
          </a-input>
        </a-form-item>
        <a-form-item label="排序值" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number :min="1" v-decorator="['sort',{'initialValue':1}]"/>
          值越小越靠前，支持小数
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>

  import pick from 'lodash.pick'
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import { addCategory, editCategory } from '@/views/sysConfig/category/service.js'

  export default {
    name: 'CategoryModal',
    components: {
      JTreeSelect
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title: '操作',
        width: 800,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },

        confirmLoading: false,
        validatorRules: {
          code: {
            rules: [{
              required: true, message: '请输入分类编码!'
            }]
          },
          pid: {},
          name: { rules: [{ required: true, message: '请输入分类名称!' }] }
        },
        url: {
        },
        expandedRowKeys: [],
        pidField: 'pid',
        subExpandedKeys: [],
        // fillRuleList: [],
        checkboxValue: [],
        fillRuleId: null
      }
    },
    created () {
    },
    methods: {
      add (record) {
        this.edit(record);
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.fillRuleId = record.fillRuleId;
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'pid', 'name', 'sort'))
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let formData = Object.assign(this.model, values);
            console.log('表单提交数据', formData)
            let obj
            if (!this.model.id) {
              obj = addCategory(formData)
            } else {
              obj = editCategory(formData)
            }
            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.submitSuccess(formData)
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'pid', 'name'))
      },
      submitSuccess(formData) {
        if (!formData.id) {
          let treeData = this.$refs.treeSelect.getCurrTreeData()
          this.expandedRowKeys = []
          this.getExpandKeysByPid(formData[this.pidField], treeData, treeData)
          if (formData.pid && this.expandedRowKeys.length === 0) {
            this.expandedRowKeys = this.subExpandedKeys;
          }
          this.$emit('ok', formData, this.expandedRowKeys.reverse());
        } else {
          this.$emit('ok', formData);
      }
      },
      getExpandKeysByPid(pid, arr, all) {
        if (pid && arr && arr.length > 0) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].key === pid) {
              this.expandedRowKeys.push(arr[i].key)
              this.getExpandKeysByPid(arr[i]['parentId'], all, all)
            } else {
              this.getExpandKeysByPid(pid, arr[i].children, all)
            }
          }
        }
      }
    }
  }
</script>
